/*
 * Copyright (C) 2009 The Rockchip Android MID Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.highglass.videoplayer;


import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.BatteryManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.hg.library.ui.BatteryViewWhite;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Formatter;
import java.util.Locale;

public class VideoController extends FrameLayout {
    private static final String TAG = "VideoController";
    private static final boolean DEBUG = false;

    private ViewGroup mControllerView;
    private VideoPlayerControl mPlayer;
    private SeekBar mProgress, mProgress_3d_left, mProgress_3d_right;

    private boolean mShowing = true;
    private boolean mDragging = false;
    private static final int sDefaultTimeout = 4000;
    private static final int FADE_OUT = 1;
    private static final int SHOW_PROGRESS = 2;
    private static final int SHOW_FAST = 3;
    static StringBuilder mFormatBuilder;
    static Formatter mFormatter;
    public long mSeekTime;

    private TextView tv_name;
    private TextView tv_name_3d_left;
    private TextView tv_name_3d_riht;

    private TextView mEndTime, mEndTime_3d_left, mEndTime_3d_right;
    private TextView mCurrentTime, mCurrentTime_3d_left, mCurrentTime_3d_right;
    private TextView mSystemTime, mSystemTime_3d_left, mSystemTime_3d_right;
    private ImageView play_iv, play_iv_3d_left, play_iv_3d_right;
    private String title;

    private RelativeLayout media_controller_2d;
    private LinearLayout media_controller_3d;

    private boolean is3DFormat = false;

    private BatteryViewWhite media_controller_2d_bvw;
    private BatteryViewWhite media_controller_2d_left_bvw;
    private BatteryViewWhite media_controller_2d_right_bvw;
    private int percent;
    private boolean isCharging;
    private boolean isFull;

    public interface VideoPlayerControl {
        void pause();

        int getDuration();

        int getCurrentPosition();

        void seekTo(int pos);

        boolean isPlaying();

        int getBufferPercentage();

        int getBrightMode();

        int getVolumeMode();
    }


    public VideoController(Context context, ViewGroup attachView, String title, int layoutRes, boolean is3DFormat) {
        super(context);
        int res = layoutRes;
        this.title = title;
        this.is3DFormat = is3DFormat;
        if (res == -1) {
            res = R.layout.media_controller;
        }
        RelativeLayout.LayoutParams ll = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        this.setLayoutParams(ll);
        mControllerView = attachView;
        inflateLayout(context, res);
//        requestFocus();
    }

    private void inflateLayout(Context context, int layoutRes) {
        LayoutInflater factory = LayoutInflater.from(context);
        mControllerView.removeAllViews();
        factory.inflate(layoutRes, mControllerView);
        contentView = factory.inflate(R.layout.line_popwindow, null);
        if (wm == null) {
            wm = (WindowManager) context.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        }
        if (wmParams == null) {
            wmParams = new WindowManager.LayoutParams();
            wmParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
            wmParams.format = PixelFormat.OPAQUE;
            wmParams.flags |= 8;
            wmParams.setTitle("PopupWindnow");
            wmParams.gravity = Gravity.LEFT | Gravity.TOP;
            wmParams.width = 1;
            wmParams.height = 1;
            wmParams.x = 0;
            wmParams.y = 0;
        }
        media_controller_2d = (RelativeLayout) mControllerView.findViewById(R.id.media_controller_2d);
        media_controller_3d = (LinearLayout) mControllerView.findViewById(R.id.media_controller_3d);


        mProgress = (SeekBar) mControllerView.findViewById(R.id.mediacontroller_progress);
        mProgress_3d_left = (SeekBar) mControllerView.findViewById(R.id.mediacontroller_progress_3d_left);
        mProgress_3d_right = (SeekBar) mControllerView.findViewById(R.id.mediacontroller_progress_3d_right);

        if (is3DFormat) {
            media_controller_3d.setVisibility(View.VISIBLE);
            media_controller_2d.setVisibility(View.GONE);
        } else {
            media_controller_3d.setVisibility(View.GONE);
            media_controller_2d.setVisibility(View.VISIBLE);
        }


        mProgress.setMax(1000);
        mProgress_3d_left.setMax(1000);
        mProgress_3d_right.setMax(1000);

        tv_name = (TextView) mControllerView.findViewById(R.id.tv_name);
        tv_name_3d_left = (TextView) mControllerView.findViewById(R.id.tv_name_3d_left);
        tv_name_3d_riht = (TextView) mControllerView.findViewById(R.id.tv_name_3d_right);
        mSystemTime = (TextView) mControllerView.findViewById(R.id.tv_system_time);
        mSystemTime_3d_left = (TextView) mControllerView.findViewById(R.id.tv_system_time_3d_left);
        mSystemTime_3d_right = (TextView) mControllerView.findViewById(R.id.tv_system_time_3d_right);
        tv_name_3d_left.setText(title);
        tv_name.setText(title);
        tv_name_3d_riht.setText(title);

        mEndTime = (TextView) mControllerView.findViewById(R.id.time_total);
        mEndTime_3d_left = (TextView) mControllerView.findViewById(R.id.time_total_3d_left);
        mEndTime_3d_right = (TextView) mControllerView.findViewById(R.id.time_total_3d_right);


        mCurrentTime = (TextView) mControllerView.findViewById(R.id.time_current);
        mCurrentTime_3d_left = (TextView) mControllerView.findViewById(R.id.time_current_3d_left);
        mCurrentTime_3d_right = (TextView) mControllerView.findViewById(R.id.time_current_3d_right);

        mFormatBuilder = new StringBuilder();
        mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());

        play_iv = (ImageView) mControllerView.findViewById(R.id.ib_play);
        play_iv_3d_left = (ImageView) mControllerView.findViewById(R.id.ib_play_3d_left);
        play_iv_3d_right = (ImageView) mControllerView.findViewById(R.id.ib_play_3d_right);

        media_controller_2d_bvw = (BatteryViewWhite) mControllerView.findViewById(R.id.media_controller_2d_bvw);
        media_controller_2d_left_bvw = (BatteryViewWhite) mControllerView.findViewById(R.id.media_controller_2d_left_bvw);
        media_controller_2d_right_bvw = (BatteryViewWhite) mControllerView.findViewById(R.id.media_controller_2d_right_bvw);
        getBatteryInfo();
    }

    public void setMediaPlayer(VideoPlayerControl player) {
        mPlayer = player;
        updatePausePlay();
    }

    /**
     * Show the controller on screen. It will go away
     * automatically after 3 seconds of inactivity.
     */
    public void show() {
        show(sDefaultTimeout);
    }

    /**
     * Show the controller on screen. It will go away
     * automatically after 'timeout' milliseconds of inactivity.
     *
     * @param timeout The timeout in milliseconds. Use 0 to show
     *                the controller until hide() is called.
     */
    public void show(int timeout) {
        if (!mShowing) {
            setProgress();
            if (mControllerView != null) {
                mControllerView.setVisibility(View.VISIBLE);
                initPopWindow();
            }

            mShowing = true;
        }
        updatePausePlay();

        // cause the progress bar to be updated even if mShowing
        // was already true.  This happens, for example, if we're
        // paused with the progress bar showing the user hits play.
        mHandler.sendEmptyMessage(SHOW_PROGRESS);

        Message msg = mHandler.obtainMessage(FADE_OUT);
        if (timeout != 0) {
            mHandler.removeMessages(FADE_OUT);
            mHandler.removeMessages(SHOW_FAST);
            mHandler.sendMessageDelayed(msg, timeout);
        }
    }

    public boolean isShowing() {
        return mShowing;
    }

    /**
     * Remove the controller from the screen.
     */
    public void hide() {
        if (mShowing) {
            try {
                mHandler.removeMessages(SHOW_PROGRESS);
                mHandler.removeMessages(SHOW_FAST);

                if (mControllerView != null) {
                    mControllerView.setVisibility(View.INVISIBLE);
                }
                hidePopWindow();
            } catch (IllegalArgumentException ex) {
                Log.w("VideoController", "already removed");
            }
            mShowing = false;
        }
    }

    View contentView;
    private WindowManager wm = null;
    private WindowManager.LayoutParams wmParams = null;

    public void initPopWindow() {
        // 声明一个弹出框
        try {
            if (contentView.getParent() == null)
                wm.addView(contentView, wmParams);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void hidePopWindow() {
        try {
            if (contentView.getParent() != null)
                wm.removeView(contentView);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int pos;
            switch (msg.what) {
                case FADE_OUT:
                    hide();
                    break;
                case SHOW_PROGRESS:
                    pos = setProgress();
                    if (mShowing && mPlayer.isPlaying()) {
                        msg = obtainMessage(SHOW_PROGRESS);
                        sendMessageDelayed(msg, 1000 - (pos % 1000));
                    }
                    break;
                case SHOW_FAST:
                    setProgress(mSeekTime);
                    if (mShowing && mPlayer.isPlaying()) {
                        msg = obtainMessage(SHOW_FAST);
                        sendMessageDelayed(msg, 200);
                    }
                    break;
            }
        }
    };

    public String stringForTime(int timeMs) {
        int totalSeconds = timeMs / 1000;

        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60);

        mFormatBuilder.setLength(0);

        if (minutes >= 100) {
            return mFormatter.format("%03d:%02d", minutes, seconds).toString();
        }
        return mFormatter.format("%02d:%02d", minutes, seconds).toString();
    }

    private int setProgress() {
        if (mPlayer == null) {
            return 0;
        }

        int position = mPlayer.getCurrentPosition();
        int duration = mPlayer.getDuration();
        if (duration == 0) {
            position = 0;
        }
        long time = System.currentTimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
        Date d1 = new Date(time);
        String t1 = format.format(d1);
        mSystemTime.setText(t1);
        mSystemTime_3d_left.setText(t1);
        mSystemTime_3d_right.setText(t1);
        if (mProgress != null) {
            if (duration > 0) {
                long pos = 1000L * position / duration;
                mProgress.setProgress((int) pos);
                mProgress_3d_left.setProgress((int) pos);
                mProgress_3d_right.setProgress((int) pos);
            }
            int percent = mPlayer.getBufferPercentage();
            mProgress.setSecondaryProgress(percent * 10);
            mProgress_3d_left.setSecondaryProgress(percent * 10);
            mProgress_3d_right.setSecondaryProgress(percent * 10);
        }

        if (mEndTime != null) {
            mEndTime.setText(stringForTime(duration));
            mEndTime_3d_left.setText(stringForTime(duration));
            mEndTime_3d_right.setText(stringForTime(duration));
        }
        if (mCurrentTime != null) {
            mCurrentTime.setText(stringForTime(position));
            mCurrentTime_3d_left.setText(stringForTime(position));
            mCurrentTime_3d_right.setText(stringForTime(position));
        }
        return position;
    }

    private int setProgress(long time) {
        if (mPlayer == null || mDragging) {
            return 0;
        }
        //int position = mPlayer.getCurrentPosition();
        int position = (int) time;
        int duration = mPlayer.getDuration();
        if (mProgress != null) {
            if (duration > 0) {
                // use long to avoid overflow
                long pos = 1000L * position / duration;
                mProgress.setProgress((int) pos);
                mProgress_3d_left.setProgress((int) pos);
                mProgress_3d_right.setProgress((int) pos);
            }
            int percent = mPlayer.getBufferPercentage();
            mProgress.setSecondaryProgress(percent * 10);
            mProgress_3d_left.setSecondaryProgress(percent * 10);
            mProgress_3d_right.setSecondaryProgress(percent * 10);
        }

        if (mEndTime != null) {
            mEndTime.setText(stringForTime(duration));
            mEndTime_3d_left.setText(stringForTime(duration));
            mEndTime_3d_right.setText(stringForTime(duration));
        }
        if (mCurrentTime != null) {
            mCurrentTime.setText(stringForTime(position));
            mCurrentTime_3d_left.setText(stringForTime(position));
            mCurrentTime_3d_right.setText(stringForTime(position));
        }

        return position;
    }

    public void updatePausePlay() {
        if (mPlayer.isPlaying()) {
            play_iv.setImageResource(R.drawable.ic_media_pause);
            play_iv_3d_left.setImageResource(R.drawable.ic_media_pause);
            play_iv_3d_right.setImageResource(R.drawable.ic_media_pause);
        } else {
            play_iv.setImageResource(R.drawable.ic_media_play);
            play_iv_3d_left.setImageResource(R.drawable.ic_media_play);
            play_iv_3d_right.setImageResource(R.drawable.ic_media_play);
        }
    }


    public void setIs3DFormat(boolean is3DFormat) {
        this.is3DFormat = is3DFormat;
        if (is3DFormat) {
            media_controller_2d.setVisibility(View.GONE);
            media_controller_3d.setVisibility(View.VISIBLE);
        } else {
            media_controller_3d.setVisibility(View.GONE);
            media_controller_2d.setVisibility(View.VISIBLE);
        }

    }

    public void setTitle(String name) {
        this.title = name;
        tv_name_3d_left.setText(title);
        tv_name.setText(title);
        tv_name_3d_riht.setText(title);
    }

    public void getBatteryStatus(Intent batteryChangedIntent) {
        final Intent intent = batteryChangedIntent;

        int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
        percent = (level * 100) / scale;
        //Toast.makeText(context,"battery="+percent,Toast.LENGTH_SHORT).show();
        int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
                BatteryManager.BATTERY_STATUS_UNKNOWN);
        String chargingType;
        isCharging = false;
        isFull = false;
        if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
            chargingType = "unknown";
            if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
                chargingType = "ac";
            } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
                chargingType = "usb";
            } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
                chargingType = "wireless";
            } else {
            }
            isCharging = true;
        } else {
            isCharging = false;
            if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
                isFull = false;
            } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
                isFull = false;
            } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
                isCharging = false;
                isFull = true;
            } else {
                isFull = false;
            }
        }
        updateLevelCharging(percent, isCharging, isFull);
    }

    private void updateLevelCharging(int percent, boolean isCharging, boolean isFull) {
        if (media_controller_2d_bvw != null && media_controller_2d_left_bvw != null && media_controller_2d_right_bvw != null) {
            media_controller_2d_bvw.setBatteryFullState(isFull);
            media_controller_2d_bvw.setBatteryPercent(percent);
            media_controller_2d_bvw.setBatteryChargingState(isCharging);

            media_controller_2d_left_bvw.setBatteryFullState(isFull);
            media_controller_2d_left_bvw.setBatteryPercent(percent);
            media_controller_2d_left_bvw.setBatteryChargingState(isCharging);

            media_controller_2d_right_bvw.setBatteryFullState(isFull);
            media_controller_2d_right_bvw.setBatteryPercent(percent);
            media_controller_2d_right_bvw.setBatteryChargingState(isCharging);
        }else{
            Log.e("fuck you","nullllllllllllll");
        }
    }

    private void getBatteryInfo() {
        if (percent == 0) {
            try {
                BufferedReader reader = new BufferedReader(new FileReader(new File("/sys/class/power_supply/battery/capacity")));
                String p = reader.readLine();
                updateLevelCharging(Integer.valueOf(p), isCharging, isFull);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            updateLevelCharging(percent, isCharging, isFull);
        }
    }
}   	

